﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ImageK.IO;
using ImageK.Measure;
using ImageK.Text;

namespace ImageK.Plugin
{
    /// <summary>
    /// Saves a table as a csv or tab-delimited text file. 
    /// </summary>
    public class MeasurementsWriter: PlugIn
    {
        public void run(String path)
        {
            save(path);
        }

        public bool save(String path)
        {
            Form frame = WindowManager.getFrontWindow();
            if (frame!=null && (frame is TextWindow) && !"Log".Equals(frame.Text)) {
                TextWindow tw = (TextWindow)frame;
                return tw.getTextPanel().saveAs(path);
            } else if (IJ.isResultsWindow())
            {
                TextPanel tp = IJ.getTextPanel();
                if (tp!=null)
                {
                    if (!tp.saveAs(path))
                        return false;
                }
            }
            else
            {
                ResultsTable rt = ResultsTable.getResultsTable();
                if (rt==null || rt.size()==0)
                {
                    frame = WindowManager.getFrame("Results");
                    if (frame==null || !(frame is TextWindow))
                        return false;
                    else
                    {
                        TextWindow tw = (TextWindow)frame;
                        return tw.getTextPanel().saveAs(path);
                    }
                }
                if (path.Equals(""))
                {
                    SaveDialog sd = new SaveDialog("Save as Text", "Results", Prefs.defaultResultsExtension());
                    String file = sd.getFileName();
                    if (file == null) return false;
                    path = sd.getDirectory() + file;
                }
                return rt.save(path);
            }
            return true;
        }
    }
}
